import store from "../store/store"
import {
  getBaseUrl
} from './permission.js'

class Request {
  constructor(options = {}) {
    this.baseUrl = options.baseUrl || ''
    this.url = options.url || ''
    this.method = 'GET'
    // 请求的参数对象
    this.data = null
    this.header = options.header || {}
    this.beforeRequest = null
    this.afterRequest = null
  }

  get(url, data = {}) {
    this.method = 'GET'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  post(url, data = {}) {
    this.method = 'POST'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  put(url, data = {}) {
    this.method = 'PUT'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  delete(url, data = {}) {
    this.method = 'DELETE'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  patch(url, data = {}) {
    this.method = 'PATCH'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }



  _() {
    // 每次请求前都重新获取 baseUrl
    console.log('当前请求的baseUrl:', this.baseUrl) // 添加日志
    console.log('当前请求的整个url为:', this.url)

    this.header = {}

    this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
    console.log('当前的请求头为', this.header)

    return new Promise((resolve, reject) => {
      let weixin = wx

      if ('undefined' !== typeof uni) {
        weixin = uni
      }

      weixin.request({
        url: this.url,
        method: this.method,
        data: this.data,
        header: this.header,
        success: (res) => {
          try {
            const result = this.responseInterceptor(res)
            resolve(result)
          } catch (error) {
            uni.$showMsg(error.message)
            reject(error)
          }
        },
        fail: (err) => {
          reject(this.handleRequestError(err))
        },
        complete: (res) => {
          // 请求完成以后做一些事情
          this.afterRequest && typeof this.afterRequest === 'function' && this.afterRequest(res)
        }
      })
    })
  }

  responseInterceptor(res) {
    console.log('响应内容：', res);

    // 1. 成功状态码（如 code === 1）
    if (res.data.code === 1) {
      return res;
    }
    // 2. 401 未授权（Token 过期）
    if (res.statusCode === 401) {
      // 清除用户信息
      store.commit('m_user/clearUserInfo');
      uni.removeStorageSync('clockState');
      store.dispatch('m_clock/RESET_STATE')
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/my/my'
      });
      // 抛出错误（错误信息供外部捕获后处理）
      throw new Error(res.data.msg || '请重新登录!');
    }

    // 3. 响应数据格式错误
    if (!res || !res.data) {
      throw new Error('响应数据格式错误!');
    }

    // 4. 其他错误（如 code !== 1 且 statusCode 不是 401）
    const errorMessage = res.data.data || res.data.msg || '请求失败!';
    throw new Error(errorMessage);
  }

  handleRequestError(err) {
    throw new Error(err || '网络请求失败')
    return uni.$showMsg(err || '网络请求失败')
  }
}

export const $http = new Request()